<template>
  <div class="bg">
    <div class="todoList">
      <h2 class="title">待办事项</h2>
      <MyHeader  @addTodo="addTodo"/>
      <div class="listItem" v-show="todos.length">
        <MyList :todos="todos"/>
        <MyFooter :todos="todos" @clearAllTodo="clearAllTodo" @checkAllTodo="checkAllTodo"/>
      </div>
    </div>
  </div>
</template>

<script>
import MyHeader from "@/components/MyHeader";
import MyList from '@/components/MyList';
import MyFooter from '@/components/MyFooter'
export default {
  name: "App",
  components:{MyHeader, MyList, MyFooter},
  data(){
    return{
      todos:JSON.parse(localStorage.getItem('todos'))||[]
    }
  },
  methods:{
    //添加一个todo
    addTodo(todoObj){
      this.todos.unshift(todoObj)
    },
    //删除一个todo
    deleteTodo(id){
      this.todos=this.todos.filter(todo=>todo.id!==id)
    },
    //勾选or取消勾选一个todo
    checkTodo(id){
      this.todos.forEach((todo)=>{
        if(todo.id===id){
          todo.done=!todo.done
        }
      })
    },
    //清除已完成任务
    clearAllTodo() {
      this.todos=this.todos.filter(todo=>!todo.done)
    },
    //全选or取消全选
    checkAllTodo(done){
      this.todos.forEach(todo=>todo.done=done)
    }
  },
  watch:{
    todos:{
      //开启深度监视
      deep:true,
      handler(value){
        localStorage.setItem('todos',JSON.stringify(value))
      }
    }
  },
  mounted(){
    //使用公共组件实现父组件和孙子组件传值
    this.$bus.$on("deleteTodo",this.deleteTodo)
    this.$bus.$on("checkTodo",this.checkTodo)
  },
  beforeDestroy() {
    //销毁公共组件的不再使用的组件
    this.$bus.$off("deleteTodo")
    this.$bus.$off("checkTodo")
  }
}
</script>

<style lang="less">
*{
  padding: 0;
  margin: 0;
}
.bg{
  background-color: #333;
  height: 937px;
  padding-top: 100px;
  box-sizing: border-box;
  .todoList{
    background-color: #fff;
    width: 50%;
    height: 90%;
    margin: 0 auto;
    //box-shadow: 5px 5px 10px 3px rgba(147, 221, 255, 0.5),-5px -5px 10px 3px rgba(147, 221, 255, 0.5);  蓝色阴影
    box-shadow: 5px 5px 10px 3px rgba(0, 0, 0, 0.5),-5px -5px 10px 3px rgba(0, 0, 0, 0.5);
    padding-top: 20px;
    box-sizing: border-box;
    .title{
      text-align: center;
      font-size: 30px;
      font-weight: 300;
      color: #00a4ff;
    }
    .listItem{
      width: 90%;
      //height: 200px;
      margin: auto;
      /*background-color: pink;*/
      list-style: none;
      border-radius: 0 0 5px 5px;
      box-shadow: 1px 1px 5px 1px rgba(0,0,0,0.1),-1px -1px 5px 1px rgba(0,0,0,0.1);
      padding: 20px 0;
      box-sizing: border-box;
    }
  }
}
</style>
